$(function () {
    var _shopId = getUrlParam("id");
    var _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
    // IScroll
    var _myScroll, _pullUpEl, _pullUpL, _pagecount = 1, _isshowend = false;
    var _contenthight = ($(window).height() - 87);
    // 计数器（用于判断单击次数，默认最新选中）
    var _tapcount = 1;
    var shopGoodsPage = function () {
        this.init();
    };

    shopGoodsPage.prototype = {
        // 初始化
        init: function () {
            this.loadShopDetail();
            this.loadShopGoodsData(true);
            this.bindEvent();
            this.initIscroll();
        },

        // 查询数据(用于切换展示样式)
        goodslistdata: [],
        // 店铺详情
        loadShopDetail: function () {
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/shop/" + _shopId
            }).done(function (res) {
                var shopitem = res;
                var html = [];
                var bannerbg = "background:url(" + CONFIG_MANAGER.imgeUrl + shopitem.banner + ") center no-repeat";
                html.push("<div class='dpbannerbg'  style='" + bannerbg + "'><div class='dpbannerbg' style='background: rgba(0, 0, 0, 0.5);'><p class='dpbannerbt'><span>" + shopitem.name + "</span><br />" + shopitem.sku_nums + "件产品 ▪ " + shopitem.shop_favorites + "人关注</p><p class='gzanniu' id='btnattention' >+ 关注</p></div></div>");

                html.push("<div class='bgbai  mbbottom'><ul class='spshu' id='shopgoodstype'>");
                html.push("<li class=' mbright hover' tip='1'><span>" + shopitem.sku_nums + "</span><br />全部商品</li>");
                html.push("<li class='mbright' tip='2'><span>" + shopitem.sku_news + "</span><br />上新商品</li>");
                html.push("<li class='mbright' tip='3'><span>" + shopitem.sku_hots + "</span><br />热门商品</li>");
                html.push("<li tip='4'><span>" + shopitem.sku_sales + "</span><br />畅销商品</li>");
                html.push("</ul></div>");

                $("#shopdeatildiv").html(html.join(""));

                if (_currentloginuser && _currentloginuser.id) {
                    $.ajax({
                            headers: {token: _currentloginuser.token},
                            type: "POST",
                            url: CONFIG_MANAGER.RequstUrl + "v1/member/favorite/isshop/" + _currentloginuser.id + "/" + _shopId
                        }
                    ).done(function (res) {
                        if (res.data == 1) {
                            $("#btnattention").addClass("gzanniu1").text("已关注");
                        }
                    }).fail(function (res) {
                        var response = JSON.parse(res.responseText);
                        if (response.Message && response.Message.indexOf("票据") > -1) {
                            $.alert("你的帐号已经在其他地方登录", function () {
                                clearLocalStorage();
                                redirect("../account/login.html");
                                return;
                            });
                        }
                    });
                }
            });
        },

        // 加载商品列表数据
        loadShopGoodsData: function (refresh) {
            var model = this;
            if (refresh) {
                _pagecount = 1;
            }
            var postdata = {
                index: _pagecount,
                size: 16,
                query: $("#searchinput").val(),
                sorting: this.condition(),
                "search": {}
            };
            var catalog = $("#categorydiv li[class=hover]").attr("tip");
            if (catalog != "0") {
                postdata.search["category"] = catalog;
            }
            var selecttype = $("#shopgoodstype").find(".hover");
            if (selecttype) {
                postdata.search["status"] = selecttype.attr("tip");
            }

            if (_pagecount == 1) {
                $.showWaiting();
            }
            $.ajax({
                headers: {'Content-Type': 'application/json'},
                type: 'POST',
                url: CONFIG_MANAGER.RequstUrl + "v1/shop/sku/" + _shopId,
                data: JSON.stringify(postdata)
            }).done(function (res) {
                var response = JSON.parse(res);
                var goodslistdata = response.data;
                model.paintGoodsItem(goodslistdata);
                model.datahandler(goodslistdata);
            }).fail(function () {

            }).always(function () {
                $.closeWaiting();
            });
        },

        // 店铺分类
        loadShopCategory: function () {
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/shop/category/lists/" + _shopId + "-0"
            }).done(function (res) {
                var rsponse = JSON.parse(res);
                if (rsponse.data) {
                    var html = [];
                    $.each(rsponse.data, function (i, item) {
                        html.push("<li tip='" + item.id + "'>" + item.name + "</li>");
                    });
                    $("#categorydiv ul").append(html.join(""));
                }
            });
        },

        // 条件
        condition: function () {
            var condition = null;
            var activeli = $('#sortTab label[class=hover]').parents("li");
            switch (activeli.attr("tip")) {
                // 推荐
                case "1":
                    condition = {"recommend ": "DESC"};
                    break;
                // 新品
                case "2":
                    condition = {"new": "DESC"};
                    break;
                // 销量
                case "3":
                    condition = {"sales": "DESC"};
                    break;
                // 价格
                case "4":
                    condition = {"price": _tapcount % 2 == 0 ? "DESC" : "ASC"};
                    break;
                default:
                    break;
            }

            return condition;
        },

        // 数据处理
        datahandler: function (goodslistdata) {
            // 显示没有查询记录
            if (goodslistdata.length == 0 && _pagecount == 1) {
                $("#pullUp").hide();
                $("#messageinfo").show();
            } else {
                $("#messageinfo").hide();
            }

            if (goodslistdata.length > 0 && _pagecount == 1) {
                this.goodslistdata = goodslistdata;
            }

            // 若我数据页码不变
            if (_pagecount != 1 && goodslistdata.length == 0) {
                _pagecount = _pagecount - 1;
            }
        },

        // 画列表
        paintGoodsItem: function (goodslistdata) {
            if (_pagecount == 1) {
                _isshowend = false;
                $("#pullUp").show();
                $("#goodsitemlist").empty();
            }

            var html = [];
            html.push("<ul class='cnxhd' style='margin-top: 0px'>");
            for (var i = 0; i < goodslistdata.length; i++) {
                var goodsitem = goodslistdata[i];
                html.push("<li class='syxhd'><div name='goodsitem' tip='" + goodsitem.sku_id + "'><dl>");
                html.push("<dt><img class='lazy' data-original='" + getImageUrl(goodsitem.logo, 496, 466) + "' src='../../images/place/496x466.png'></dt>");
                html.push("<dd class='dpmc'>" + goodsitem.shop_name + "</dd>");
                html.push("<dd class='spjj'>" + goodsitem.name + goodsitem.specs + "</dd>");
                html.push("<dd class='spjj'>" + goodsitem.title + "</dd>");
                html.push("<dd class='spjge'><span>￥" + goodsitem.shop_price + "</span><i>市场价：" + goodsitem.market_price + "</i></dd>");
                html.push("</dl></div></li>");
            }
            html.push("</ul>");

            // 显示END
            if ((_pagecount > 1 && goodslistdata.length == 0) || (goodslistdata.length > 0 && _pagecount == 1 && goodslistdata.length < 16)) {
                _isshowend = true;
                $("#pullUp").hide();
                html.push("<div id='enddiv' style='margin-top:18px;margin-bottom: 20px;'><div class='with-line'>看完了</div></div>");
            }

            $("#goodsitemlist").append(html.join(""));
            $('img.lazy').lazyload({placeholder: "../../images/white.gif", threshold: 100, failure_limit: 10});
            _myScroll.refresh();
        },

        // 绑定事件
        bindEvent: function () {
            var model = this;
            // 返回
            $("#back").on("tap", function () {
                back();
            });

            var hasInitCategory = false;
            // 店铺商品分类
            $("#btncategory").on("tap", function () {
                if (!hasInitCategory) {
                    model.loadShopCategory();
                    hasInitCategory = true;
                }
                $("#categorybgdiv").show();
                $("#categorydiv").show();
                setTimeout(function () {
                    $("#categorydiv ul").addClass("moveFromRight-moved");
                }, 100);
            });

            // 分类页面
            $("#categorybgdiv").on("tap", function () {
                $("#categorydiv ul").removeClass("moveFromRight-moved");
                setTimeout(function () {
                    $("#categorybgdiv").hide();
                    $("#categorydiv").hide();
                }, 300);
            });

            // 分类过滤
            $("#categorydiv").on("tap", "li", function () {
                $("#categorydiv li[class=hover]").removeClass("hover");
                $(this).addClass("hover");
                $("#categorydiv ul").removeClass("moveFromRight-moved");
                setTimeout(function () {
                    $("#categorybgdiv").hide();
                    $("#categorydiv").hide();
                }, 200);

                model.loadShopGoodsData(true);
            });

            // 置顶
            $("#gotop").on("click", function () {
                _myScroll.scrollTo(0, 0, 800);
                $('html,body').animate({scrollTop: '0px'}, 500);
            });

            // 关注
            $("#shopdeatildiv").on("click", "#btnattention", function () {
                if (!_currentloginuser) {
                    // 用户若无登录，必须登录
                    redirect("../account/login.html");
                    return;
                }

                if ($(this).text() == "已关注") {
                    $(this).removeClass("gzanniu1").text("+ 关注");
                    $.ajax({
                        headers: {token: _currentloginuser.token},
                        type: "DELETE",
                        url: CONFIG_MANAGER.RequstUrl + "v1/member/favorite/shop/" + _currentloginuser.id + "/" + _shopId
                    }).done(function (res) {

                    }).fail(function (res) {
                        var response = JSON.parse(res.responseText);
                        if (response.Message && response.Message.indexOf("票据") > -1) {
                            $.alert("你的帐号已经在其他地方登录", function () {
                                clearLocalStorage();
                                redirect("../account/login.html");
                                return;
                            });
                        }
                    });
                } else {
                    $(this).addClass("gzanniu1").text("已关注");
                    $.ajax({
                        headers: {token: _currentloginuser.token},
                        type: "POST",
                        url: CONFIG_MANAGER.RequstUrl + "v1/member/favorite/shop/" + _currentloginuser.id + "/" + _shopId
                    }).done(function (res) {

                    }).fail(function (res) {
                        var response = JSON.parse(res.responseText);
                        if (response.Message && response.Message.indexOf("票据") > -1) {
                            $.alert("你的帐号已经在其他地方登录", function () {
                                clearLocalStorage();
                                redirect("../account/login.html");
                                return;
                            });
                        }
                    });
                }
            });

            // 领取优惠券
            $("#couponlist li").on("click", function () {
                if ($(this).hasClass("yhquan-ylq")) {
                    return;
                }
                $(this).addClass("yhquan-ylq").find("div").show();
            });

            // 全部/热销产品
            $("#shopdeatildiv").on("click", "#shopgoodstype li", function () {
                $("#shopgoodstype li").removeClass("hover");
                $(this).addClass("hover");

                model.loadShopGoodsData(true);
            });

            // 排序Tab
            var activeli = $('#sortTab li:first-child');
            $("#sortTab li").on("click", function () {
                var targetli = $(this);
                var targetlitip = targetli.attr("tip");

                //  推荐 / 新品 / 销量
                if (["1", "2", "3"].indexOf(targetlitip) > -1) {
                    if (activeli.attr("tip") == targetlitip) {
                        return;
                    }
                    targetli.find("label").addClass("hover");
                    activeli.find("label").removeClass("hover");
                    activeli.find("i").removeClass("hover");
                } else {  // 价格
                    if (activeli.attr("tip") == targetlitip) {
                        _tapcount = _tapcount + 1;
                        if (_tapcount % 2 == 0) {
                            $(targetli.find("i")[1]).addClass("hover");
                            $(targetli.find("i")[0]).removeClass("hover");
                        } else {
                            $(targetli.find("i")[0]).addClass("hover");
                            $(targetli.find("i")[1]).removeClass("hover");
                        }
                    } else {
                        _tapcount = 1;
                        targetli.find("label").addClass("hover");
                        $(targetli.find("i")[0]).addClass("hover");
                        activeli.find("label").removeClass("hover");
                    }
                }
                var value = "translateX(" + $(this).offset().left + "px)";
                $("#currenttab").css({
                    "margin-left": "0px",
                    "transform": value,
                    "-moz-transform": value,
                    "-webkit-transform": value,
                    "-o-transform": value,
                    "-ms-transform": value
                });
                activeli = targetli;
                model.loadShopGoodsData(true);
            });

            // 搜索
            $("#searchdiv").on("tap", function () {
                showSearchPage();
            });

            // 搜索页遮罩层
            $("#seachbgdiv").on("tap", function () {
                closeSearchPage();
            });

            // 商品详情
            $("#goodsitemlist").on("click", "div[name=goodsitem]", function () {
                redirect("../goods/goodsdetail.html?id=" + $(this).attr("tip"));
            });

        },


        // 判断显示置顶图标
        isDisplayTopIcon: function (y) {
            var top = (y * -1);
            if (top > _contenthight / 2) {
                $('#gotop').show();
            } else {
                $('#gotop').hide();
            }
        },

        // 初始化Iscroll
        initIscroll: function () {
            var model = this;
            _pullUpEl = $('#pullUp');
            _pullUpL = _pullUpEl.find('._pullUpLabel');

            _myScroll = new IScroll('#wrapper', {
                probeType: 3,
                scrollbars: true,
                mouseWheel: false,
                fadeScrollbars: true,
                bounce: true,
                interactiveScrollbars: false,
                shrinkScrollbars: 'scale',
                click: true,
                momentum: true
            });
            //滚动时
            _myScroll.on('scroll', function () {

            });
            //滚动完毕
            _myScroll.on('scrollEnd', function () {
                if (this.y <= 5 && this.y < (this.maxScrollY + 10)) {
                    if (!_isshowend) {
                        pullUpAction();
                    }
                }
                if (this.y < -310) {
                    $(".tabdiv").show();
                } else {
                    $(".tabdiv").hide();
                }
                $('img.lazy').lazyload({
                    placeholder: "../../images/grey.gif",
                    container: $("#wrapper"),
                    threshold: 100,
                    failure_limit: 10
                });
                model.isDisplayTopIcon(this.y);
            });

            // 上拉显示更多
            function pullUpAction() {
                setTimeout(function () {
                    _pagecount = _pagecount + 1;
                    model.loadShopGoodsData();
                    _pullUpEl.removeClass('loading');
                    _pullUpL.html('上拉显示更多...');
                    _myScroll.refresh();
                }, 1000);
            }

            document.addEventListener('touchmove', function (e) {

            }, false);
        }
    };

    var shopGoodsPage = new shopGoodsPage();
    search = function (searchword) {
        $("#searchinput").val(searchword);
        shopGoodsPage.loadShopGoodsData(true);
    }
});
// 关闭搜索页
function showSearchPage() {
    $("#seachbgdiv").show();
    $("#searchiframe").show();
    setTimeout(function () {
        searchiframe.window.show($("#searchinput").val());
    }, 300);
}

// 关闭搜索页
function closeSearchPage() {
    $("#searchiframe").hide();
    $("#seachbgdiv").hide();
}
// 搜索
function search() {}